// DumpTCPPayloadDoc.cpp : implementation of the CDumpTCPPayloadDoc class
//

#include "stdafx.h"
#include "DumpTCPPayload.h"

#include "DumpTCPPayloadDoc.h"

#include "mynetworkanalyzer.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CDumpTCPPayloadDoc

IMPLEMENT_DYNCREATE(CDumpTCPPayloadDoc, CDocument)

BEGIN_MESSAGE_MAP(CDumpTCPPayloadDoc, CDocument)
END_MESSAGE_MAP()


// CDumpTCPPayloadDoc construction/destruction

CDumpTCPPayloadDoc::CDumpTCPPayloadDoc()
{
	// TODO: add one-time construction code here
	analyzer = new MyNetworkAnalyzer();

}

CDumpTCPPayloadDoc::~CDumpTCPPayloadDoc()
{
	delete analyzer;
}

BOOL CDumpTCPPayloadDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)

	return TRUE;
}




// CDumpTCPPayloadDoc serialization

void CDumpTCPPayloadDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here	
		int i=0;
		TCHAR szIdx[16]={0};
		TCHAR* pText=NULL;
		
		CString strPath = GetPathName();
		strPath = strPath.Left(  strPath.ReverseFind( _T('\\') ) +1 );
		if ( strPath.Find( _T('\\') ) < 0 ) strPath += _T("\\");
		strPath += _T("bin");
		CreateDirectory(strPath, NULL);

		for(TDumps::iterator it= m_dumps.begin(); it != m_dumps.end();it ++,i++ )
		{
			CStdioFile binFile;

			CDumpInfo* info = *it;
			_itot(i,szIdx,10);
			ar.WriteString( szIdx );
			ar.WriteString( _T(" ") );

			BOOL bIsBinFileOK = binFile.Open( strPath + _T("\\") +  szIdx + _T(".bin") , CFile::modeCreate | CFile::modeWrite ) ;
			
			extern TCHAR* FormatIPPort(ULONG ip,ULONG port);
			pText = FormatIPPort(info->srcIP,info->srcPort);
			ar.WriteString( pText );
			ar.WriteString( _T(" ") );

			pText = FormatIPPort(info->dstIP,info->dstPort) ;			
			ar.WriteString( pText );
			ar.WriteString( _T(" ") );

			_itot( info->dataLengh, szIdx,10);
			ar.WriteString( szIdx );
			ar.WriteString( _T(" ") );

			extern TCHAR* FormatData( CDumpInfo* info);
			pText = FormatData(info);
			ar.WriteString( pText );
			ar.WriteString(_T("\n") );


			if( bIsBinFileOK ) binFile.Write( info->data, info->dataLengh );
			binFile.Close();
		}
	}
	else
	{
		// TODO: add loading code here
	}
}


// CDumpTCPPayloadDoc diagnostics

#ifdef _DEBUG
void CDumpTCPPayloadDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CDumpTCPPayloadDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG


// CDumpTCPPayloadDoc commands

BOOL CDumpTCPPayloadDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
	if (!CDocument::OnOpenDocument(lpszPathName))
		return FALSE;

	// TODO:  Add your specialized creation code here
	return TRUE;
}
